package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.entity.domain.business.BusinessDO;
import com.qk.entity.domain.user.UserDO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.entity.Customer;
import com.qk.entity.dto.business.BusinessDTO;
import com.qk.entity.dto.business.BusinessListDTO;
import com.qk.entity.dto.business.BusinessPoolDTO;
import com.qk.entity.dto.business.UpdateBusinessInfoDTO;
import com.qk.entity.vo.business.BusinessVO;
import com.qk.management.mapper.*;
import com.qk.management.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author fantuan
 * @created 2025/10/15 10:53
 * @description
 */
@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public PageResult<BusinessDO> selectBusinessList(BusinessListDTO dto) {
        Page<Object> pages = new Page<>(dto.getPage(),dto.getPageSize());
        Page<BusinessDO> businessDOPage = this.baseMapper.selectBusinessList(pages,dto);
        return PageResult.<BusinessDO>builder()
                .total(Long.valueOf(businessDOPage.getTotal()).intValue())
                .rows(businessDOPage.getRecords())
                .build();

    }

    @Override
    public void addBusiness(BusinessDTO dto) {
        if(ObjectUtil.isEmpty(dto.getName()) || ObjectUtil.isEmpty(dto.getPhone())){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setStatus(1);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.insert(business);
    }

    @Override
    public void updateBusinessById(Integer businessId, Integer userId) {
        Business business = this.baseMapper.selectById(businessId);
        business.setStatus(BusinessStatusConstants.WAIT_FOLLOW_UP);
        business.setUserId(userId);
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(business);
    }

    @Override
    public BusinessVO selectBusinessById(Integer id) {
        Business business = this.baseMapper.selectById(id);
        Integer userId = business.getUserId();
        UserDO user = userMapper.getUserById(userId);
        List<BusinessTrackRecord> trackRecords = businessTrackRecordMapper.selectList(Wrappers.lambdaQuery(BusinessTrackRecord.class)
                .in(BusinessTrackRecord::getBusinessId,id));
        BusinessVO businessVO = BeanUtil.copyProperties(business, BusinessVO.class);
        List<BusinessVO.BusinessTrackRecordVO> list = trackRecords.stream().map(item -> {
            BusinessVO.BusinessTrackRecordVO vo = BeanUtil.copyProperties(item, BusinessVO.BusinessTrackRecordVO.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        businessVO.setTrackRecords(list);
        return businessVO;
    }

    @Transactional
    @Override
    public void updateBusinessInfo(UpdateBusinessInfoDTO dto) {
        if(ObjectUtil.isEmpty(dto.getName())){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Business business = this.baseMapper.selectById(dto.getId());
        business.setStatus(BusinessStatusConstants.FOLLOW_UP);
        business.setNextTime(dto.getNextTime());
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(business);
        BusinessTrackRecord businessTrackRecord = BeanUtil.copyProperties(dto, BusinessTrackRecord.class);
        businessTrackRecord.setCreateTime(LocalDateTime.now());
        businessTrackRecord.setId(null);
        businessTrackRecord.setBusinessId(dto.getId());
        businessTrackRecord.setUserId(CurrentUserContextHolders.get());
        businessTrackRecordMapper.insert(businessTrackRecord);
    }


    @Override
    public void backBusinessById(Integer id) {
        Business business = this.baseMapper.selectById(id);
        business.setStatus(BusinessStatusConstants.RECYCLE);
        this.baseMapper.updateById(business);
    }

    @Override
    public PageResult<Business> selectBusinessPool(BusinessPoolDTO dto) {
        Page<Object> pages = new Page<>(dto.getPage(),dto.getPageSize());
        Page<Business> businessPage = this.baseMapper.selectBusinessPool(pages,dto);
        return PageResult.<Business>builder()
                .total(Long.valueOf(businessPage.getTotal()).intValue())
                .rows(businessPage.getRecords())
                .build();
    }

    @Transactional
    @Override
    public void toCustomerById(Integer id) {
        Business business = this.baseMapper.selectById(id);
        business.setStatus(BusinessStatusConstants.CONVERT_CUSTOMER);
        this.baseMapper.updateById(business);
        Customer customer = BeanUtil.copyProperties(business, Customer.class);
        customer.setId(null);
        customer.setCreateTime(LocalDateTime.now());
        customer.setUpdateTime(LocalDateTime.now());
        customer.setBusinessId(id);
        customerMapper.insert(customer);
    }
}
